<template>
  <div class="app-container">
    <el-card>
      <el-page-header @back="goBack">
        <template #content>
          <div class="flex items-center">
            <div v-if="!route.query?.id">新增纸张领用单</div>
            <div v-else>
              <span
                class="text-sm mr-2"
                style="color: var(--el-text-color-regular)"
              >
                纸张领用单编码:
              </span>
              <el-tag>{{ form.useNum }}</el-tag>
            </div>
          </div>
        </template>
        <template #extra>
          <div class="flex items-center" v-if="!route.query.info">
            <el-button type="primary" :loading="btnLoading" @click="submitForm"
              >保 存</el-button
            >
          </div>
        </template>
      </el-page-header>
    </el-card>
    <el-card style="margin-top: 10px">
      <el-collapse v-model="activeNames">
        <el-collapse-item disabled title="基本信息" name="1">
          <template #title>
            <el-icon style="color: #4479f6">
              <Position />
            </el-icon>
            <span class="title">基本信息</span>
          </template>
          <div>
            <el-form
              :model="form"
              :rules="rules"
              :disabled="flag"
              ref="userRef"
              label-width="100px"
            >
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="领用人" prop="picker">
                    <el-input
                      v-model="form.picker"
                      readonly
                      placeholder=""
                      maxlength="18"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="领用机台" prop="machineName">
                    <el-input
                      v-model="form.machineName"
                      readonly
                      placeholder="请选择机台"
                      @click="openDialog"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="车间" prop="workshopName">
                    <el-input
                      v-model="form.workshopName"
                      readonly
                      placeholder="自动带出"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <!-- <el-col :span="8">
                                    <el-form-item label="类型" prop="type">
                                        <el-select
                                            v-model="form.type"
                                            class="m-2"
                                            @change="changeType"
                                            placeholder="请选择类型"
                                            style="width: 100%"
                                        >
                                            <el-option
                                                v-for="item in mes_paper_package"
                                                :key="item.label"
                                                :label="item.label"
                                                :value="item.value"
                                            />
                                        </el-select>
                                    </el-form-item>
                                </el-col> -->
                <el-col :span="8">
                  <el-form-item label="仓库" prop="storeName">
                    <el-input
                      v-model="form.storeName"
                      readonly
                      placeholder="仓库"
                    />

                    <!--  @click="openDialogWarehouse"
                                             :disabled="outOpen" -->
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="出库时间" prop="outboundDate">
                    <el-date-picker
                      style="width: 100%"
                      v-model="form.outboundDate"
                      format="YYYY-MM-DD HH:mm:ss"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      type="datetime"
                      placeholder="请选择时间"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="创建人" prop="createBy">
                    <el-input v-model="form.createBy" readonly placeholder="" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="创建时间" prop="createTime">
                    <el-date-picker
                      style="width: 100%"
                      readonly
                      v-model="form.createTime"
                      format="YYYY-MM-DD HH:mm:ss"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      type="datetime"
                      placeholder="请选择时间"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="备注">
                    <el-input
                      v-model="form.remark"
                      type="textarea"
                      placeholder="请输入内容"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-collapse-item>
        <el-collapse-item disabled title="领用明细" name="2">
          <template #title>
            <el-icon style="color: #4479f6">
              <Position />
            </el-icon>
            <span class="title">领用明细</span>
          </template>
          <el-button
            v-if="!flag"
            style="margin-bottom: 10px"
            type="primary"
            size="small"
            @click="handleAddStorage"
          >
            选择纸张
          </el-button>
          <el-table
            v-loading="loading"
            class="table-form"
            :data="mesUseDetailList"
          >
            <el-table-column
              label="序号"
              width="60"
              type="index"
              align="center"
            ></el-table-column>
            <!-- <el-table-column
                            label="生产单编码"
                            align="center"
                            width="150"
                            :show-overflow-tooltip="true"
                            prop="produceNo"
                        ></el-table-column>
                        <el-table-column
                            label="订单编码"
                            align="center"
                            width="150"
                            :show-overflow-tooltip="true"
                            prop="orderNo"
                        ></el-table-column>
                        <el-table-column
                            label="书刊名称"
                            align="center"
                            width="280"
                            :show-overflow-tooltip="true"
                            prop="bookName"
                        ></el-table-column> -->
            <el-table-column
              label="纸张编码"
              width="160"
              align="center"
              prop="code"
            ></el-table-column>
            <el-table-column
              label="纸张名称"
              width="160"
              align="center"
              prop="name"
            ></el-table-column>
            <el-table-column
              label="规格"
              align="center"
              width="110"
              prop="specs"
            >
              <template #default="scope">
                <span v-if="scope.row.longWide">
                  {{ scope.row.longWide }}
                </span>
                <span v-if="scope.row.specs">
                  <dict-tag
                    :options="mes_paper_specs"
                    :value="scope.row.specs"
                  />
                </span>
              </template>
              <!-- <template #default="scope">
                                <dict-tag :options="mes_paper_specs" :value="scope.row.specs" />
                            </template> -->
            </el-table-column>
            <el-table-column
              label="定量"
              width="80"
              align="center"
              prop="weight"
            ></el-table-column>
            <el-table-column label="品牌" align="center" prop="brand">
              <template #default="scope">
                <dict-tag :options="mes_paper_brand" :value="scope.row.brand" />
              </template>
            </el-table-column>
            <el-table-column
              label="纸型"
              align="center"
              width="100"
              prop="paperType"
            >
              <template #default="scope">
                <dict-tag
                  :options="mes_paper_type"
                  :value="scope.row.paperType"
                />
              </template>
            </el-table-column>
            <el-table-column
              label="单位"
              width="80"
              align="center"
              :show-overflow-tooltip="true"
              prop="unit"
            >
              <template #default="scope">
                <dict-tag :options="mes_paper_unit" :value="scope.row.unit" />
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="领用数量"
              min-width="120"
              prop="useNumber"
              :show-overflow-tooltip="true"
            >
              <template #default="scope">
                <el-form-item>
                  <el-input
                    type="number"
                    @input="limitInput('useNumber', scope.row)"
                    :disabled="flag"
                    v-model="scope.row.useNumber"
                    placeholder="请输入"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <!-- <el-table-column
                            align="center"
                            label="已领用数量"
                            min-width="100"
                            prop="beforeuseNumber"
                            :show-overflow-tooltip="true"
                        ></el-table-column>
                        <el-table-column
                            align="center"
                            label="未领用数量"
                            min-width="120"
                            prop="notuseNumber"
                            :show-overflow-tooltip="true"
                        ></el-table-column>
                        <el-table-column
                            align="center"
                            label="版材尺寸"
                            min-width="120"
                            prop="plateSize"
                            :show-overflow-tooltip="true"
                        >
                            <template #default="scope">
                                <el-form-item>
                                    <el-input
                                        type="number"
                                        :disabled="flag"
                                        v-model.number="scope.row.plateSize"
                                        placeholder="请输入"
                                    ></el-input>
                                </el-form-item>
                            </template>
                        </el-table-column> -->
            <el-table-column
              label="备注"
              width="120"
              align="center"
              prop="useRemark"
              :show-overflow-tooltip="true"
            >
              <template #default="scope">
                <span v-if="flag">{{ scope.row.useRemark }}</span>
                <el-form-item v-else>
                  <el-input
                    v-model="scope.row.useRemark"
                    placeholder="请输入"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              v-if="!flag"
              align="center"
              fixed="right"
              class-name="small-padding fixed-width"
            >
              <template #default="scope">
                <el-tooltip content="删除" placement="top">
                  <el-button
                    link
                    type="primary"
                    icon="Delete"
                    @click="handleDelete(scope.row)"
                  ></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </el-collapse-item>
      </el-collapse>
    </el-card>
    <!-- 领用库单明细 -->
    <!-- <orderList
            :visible="orderListOpen"
            @changeUpdate="changeOrderData"
            :orderSelectList="orderSelectList"
            :machineId="machineId"
            :paperType="paperType"
            @cancel="
                () => {
                    orderListOpen = false
                }
            "
        ></orderList> -->
    <paperListVue
      :visible="paperVisible"
      :packageType="searchType"
      @changeUpdate="changeOrderData"
      @cancel="
        () => {
          paperVisible = false;
        }
      "
      :paperSelectList="paperSelectList"
    ></paperListVue>
    <SearchWorkBench
      :visible="searchVisible"
      @changeUpdate="changeWorkBenchData"
      :search="{ type: '2', model }"
      @cancel="
        () => {
          searchVisible = false;
        }
      "
    ></SearchWorkBench>
    <SearchWorkBenchWarehouse
      :visible="searchVisibleWarehouse"
      @changeUpdate="changeWorkBenchDataWarehouse"
      :search="{ type: '5' }"
      @cancel="
        () => {
          searchVisibleWarehouse = false;
        }
      "
    ></SearchWorkBenchWarehouse>
  </div>
</template>

<script setup>
import SearchWorkBench from "./searchWorkBranch.vue";
import SearchWorkBenchWarehouse from "@/components/SearchWorkBench";
import paperListVue from "./paperList.vue";
import { toNumber } from "@/utils/ruoyi";
import {
  addUseInfo,
  editUseInfo,
  getUseInfo,
} from "@/api/storage/paperAccess.js";
import useTagsViewStore from "@/store/modules/tagsView";
import useUserStore from "@/store/modules/user";
import { ElMessage } from "element-plus";
import { nextTick } from "vue";
const tagsViewStore = useTagsViewStore();
const { proxy } = getCurrentInstance();
const {
  mes_paper_specs,
  mes_paper_package,
  mes_paper_type,
  mes_paper_unit,
  mes_paper_brand,
} = proxy.useDict(
  "mes_paper_specs",
  "mes_paper_type",
  "mes_paper_unit",
  "mes_paper_brand",
  "mes_paper_package"
);
const route = useRoute();
const router = useRouter();
const machineId = ref("");
const searchVisible = ref(false);
const paperVisible = ref(false);
const outOpen = ref(true);
const paperSelectList = ref([]);
const activeNames = ["1", "2"];
const userRef = ref(null);
const flag = ref(false);
const paperType = ref("");
const searchType = ref("");
const loading = ref(false);
const searchVisibleWarehouse = ref(false);
const model = ref(undefined);
const btnLoading = ref(false);
const userInfo = useUserStore();
const data = reactive({
  form: {},
  mesUseDetailList: [],
  rules: {
    machineName: [
      { required: true, message: "领用机台不能为空", trigger: "change" },
    ],
    type: [{ required: true, message: "类型不能为空", trigger: "change" }],
    outboundDate: [
      {
        required: true,
        message: "出库时间不能为空",
        trigger: ["blur", "change"],
      },
    ],
  },
});

const { form, rules, mesUseDetailList } = toRefs(data);
// 权限
const permissions = useUserStore().roles;
if (permissions.includes("ddcq")) {
  model.value = "1";
} else if (permissions.includes("zzzzc")) {
  model.value = "2";
}
//限制只能输入4位小数
function limitInput(key, row) {
  row[key] =
    ("" + row[key]) // 第一步：转成字符串
      .replace(/[^\d^\.]+/g, "")
      .replace(/^0+(\d)/, "$1")
      .replace(/^\./, "0.")
      .match(/^\d*(\.?\d{0,4})/g)[0] || "";
}

nextTick(() => {
  form.value.createBy = userInfo.name;
  form.value.picker = userInfo.name;
});

if (route.query.id) {
  getUseInfo(route.query.id).then((res) => {
    Object.assign(form.value, { ...res.data });
    mesUseDetailList.value = res.data.mesUseDetailList.map((item) => {
      return {
        ...item,
        ...item.mesPaper,
      };
    });
    if (route.query.info) {
      flag.value = true;
    }
  });
} else {
  flag.value = false;
  form.value = {};
  mesUseDetailList.value = [];
}

// const changeType = row => {
//     if (row == 1) {
//         outOpen.value = false
//     } else {
//         outOpen.value = true
//         form.value.outMachineName = undefined
//         form.value.outMachineid = undefined
//     }
// }
const changeType = (row) => {
  console.log(row, "packageType");
  if (row == 1) {
    form.value.storeName = "白纸裁切组";
  } else {
    form.value.storeName = "纸库";
  }
  searchType.value = row;
};
// 选择仓库
const openDialogWarehouse = () => {
  searchVisibleWarehouse.value = true;
};
// 选中的仓库
const changeWorkBenchDataWarehouse = (row) => {
  mesUseDetailList.value = [];
  form.value.outMachineName = row.machineName;
  form.value.outMachineid = row.pid;
  searchVisibleWarehouse.value = false;
};
// 获取当前时间
const getCurrentDateTime = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0");
  const day = String(now.getDate()).padStart(2, "0");
  const hours = String(now.getHours()).padStart(2, "0");
  const minutes = String(now.getMinutes()).padStart(2, "0");
  const seconds = String(now.getSeconds()).padStart(2, "0");
  form.value.createTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  form.value.outboundDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};
getCurrentDateTime();

// 打开机台页面
const openDialog = () => {
  searchVisible.value = true;
};
// 选中的机台
const changeWorkBenchData = (row) => {
  mesUseDetailList.value = [];
  // if (form.value.type != row.model) {
  //     mesUseDetailList.value = []
  // }
  form.value.machineName = row.machineName;
  form.value.useMachineid = row.pid;
  form.value.type = row.model; // 平张 卷轮
  searchType.value = row.model;
  form.value.workshopName = row.workshopName;
  searchVisible.value = false;
};

// 新增入库明细
const handleAddStorage = () => {
  if (!form.value.useMachineid) {
    return ElMessage({
      message: "请选择机台",
      type: "warning",
    });
  }
  // if (form.value.storeName == '白纸裁切组') {
  //     searchType.value = 1
  // } else {
  //     searchType.value = 2
  // }

  // machineId.value = form.value.useMachineid
  // paperType.value = form.value.type
  paperSelectList.value = mesUseDetailList.value;
  paperVisible.value = true;
};
// 选中的入库明细
const changeOrderData = (row) => {
  const codeSet = new Set(mesUseDetailList.value.map((data) => data.paperid));
  row.forEach((item) => {
    if (!codeSet.has(item.paperid)) {
      mesUseDetailList.value.push({ ...item });
      codeSet.add(item.paperid);
    }
  });
  paperVisible.value = false;
};

// 删除
const handleDelete = (row) => {
  proxy.$modal.confirm("是否确认删除该数据？").then(function () {
    mesUseDetailList.value = mesUseDetailList.value.filter((item) =>
      item.paperid ? item.paperid != row.paperid : item.id != row.id
    );
    proxy.$modal.msgSuccess("删除成功");
  });
};
// 确认
const submitForm = () => {
  userRef.value.validate((valid) => {
    if (valid) {
      btnLoading.value = true;
      if (route.query.id) {
        editUseInfo({
          ...form.value,
          status: 1,
          mesUseDetailList: mesUseDetailList.value,
        })
          .then((res) => {
            ElMessage({
              message: "编辑成功",
              type: "success",
            });
            goBack();
          })
          .catch((err) => {
            btnLoading.value = false;
          });
      } else {
        addUseInfo({
          ...form.value,
          status: 1,
          mesUseDetailList: mesUseDetailList.value,
        })
          .then((res) => {
            ElMessage({
              message: "新增成功",
              type: "success",
            });
            goBack();
          })
          .catch((err) => {
            btnLoading.value = false;
          });
      }
    }
  });
};
//  返回
const goBack = () => {
  tagsViewStore.delView(route);
  router.go(-1);
  // router.push('/storage/paperAccess')
};
</script>

<style lang="scss" scoped>
.footer {
  text-align: center;
}

:deep(.el-pagination) {
  position: unset;
}

.table-form :deep(.el-form-item) {
  margin-bottom: 0;
}
</style>
